<?php

class Sistema_GradetamanhosController extends App_Controller_Action
{

    private $_table     = 'GRADETAMANHOS';
    private $_pk        = 'GRA_ID';
    private $_order_col = 'GRA_NOM';
    private $_order     = 'ASC';
    private $_sta_col   = 'GRA_STA';
    private $obj        = '';
    private $form       = '';
    private $_file_col  = 'GRA_FILE'; 
    public  $dir = 'public/upload/gradetamanhos/';
    //public  $db = '';
     
    public function init()
    {   
        //$this->db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $this->obj = new Sistema_Model_DbTable_Gradetamanhos();
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Sistema_Form_Gradetamanhos();
    }

    public function indexAction() {
        Zend_Loader::loadClass('tools','library');
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('elemform','library');
        Zend_Loader::loadClass('datetools','library');
        
        $where = $this->_pk . ' > 0';
       
        $STA = $this->_getParam($this->_sta_col, 1);
        $where .= ' and ' . $this->_sta_col . ' = ' . $STA;
        
        $sessao = new Zend_Session_Namespace('filtro_'.$this->_controller);
        
        $dscfiltro = $this->_getParam('dscfiltro', ''); 
        
        if($dscfiltro != '' || $sessao->dscfiltro > ''){
            if($dscfiltro == '') $dscfiltro = $sessao->dscfiltro;
            $sessao->dscfiltro = $dscfiltro;
            
            $where .= ' and (GRA_NOM like "%'. $dscfiltro.'%")';
            
        } 
        
        $this->view->dscfiltro = $dscfiltro;
        
        //$result = $this->obj->fetchAll($this->obj->select()->where($where)->order($this->_order_col.' '.$this->_order));
        $query = 'SELECT SQL_CACHE * FROM GRADETAMANHOS WHERE '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
    
        $this->view->db = $this->db;
    }
    
    public function editAction() {
        
        Zend_Loader::loadClass('imagem','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_geral.js');
        
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_gradetamanhos.js');
        
        
        $this->view->form = $this->form;
        if($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if ($this->form->isValid($formData)) {
                    $id = (int) $this->form->getValue($this->_pk);
                    
                    $nome_img = $id.'_tabtam';
                    $returnImg = imagem::upload($this->_file_col,$this->dir,$nome_img);
                    
                    $data = $this->form->getValues();
                    
                    unset($data[$this->_file_col]);
                    unset($data['img']);
                    unset($data['img2']);
                    unset($data['TAM_IDS']);
                    unset($data['LGM_IDS']);
                    unset($data['SEG_IDS']);
                    
                    if($id == 0){
                        $this->obj->insert($data);
                        $id =  $this->obj->getAdapter()->lastInsertId();   
                        $nome_img = $id.'_tabtam';
                        imagem::rename($nome_img,$this->dir,$returnImg['filenew']);
                        
                        foreach($formData['TAM_ID'] as $tam) {
                            $obj = new Sistema_Model_DbTable_GradetamanhosHasTamanhos();
                            $newData = array('GRA_ID'=>$id , 'TAM_ID'=>$tam);
                            $obj->insert($newData);
                        }
                        
                        foreach($formData['LGM_ID'] as $lgm) {
                            $obj = new Sistema_Model_DbTable_GradetamanhosHasLegendaMedidas();
                            $newData = array('GRA_ID'=>$id , 'LGM_ID'=>$lgm);
                            $obj->insert($newData);
                        }
                        
                        $fsc = new Sistema_Model_DbTable_GradetamanhosHasCat();
                        foreach($formData['SEG_CAT'] as $key => $arr_seg){
                            foreach($arr_seg as $seg){
                                $data_arr = array(
                                    'GRA_ID' => $id,
                                    'CTS_ID' => $key,
                                    'CAT_ID' => $seg,
                                );
                                $fsc->insert($data_arr);
                            }
                        }
                    }
                    else {
                        
                        $this->obj->update($data, $this->_pk.' = ' . $id);
                        $obj = new Sistema_Model_DbTable_GradetamanhosHasTamanhos();
                        $obj->delete('GRA_ID = '.$id);
                        foreach($formData['TAM_ID'] as $tam) {
                            $newData = array('GRA_ID'=>$id , 'TAM_ID'=>$tam);
                            $obj->insert($newData);
                        }
                        
                        $obj = new Sistema_Model_DbTable_GradetamanhosHasLegendaMedidas();
                        $obj->delete('GRA_ID = '.$id);
                        foreach($formData['LGM_ID'] as $lgm) {
                            $obj = new Sistema_Model_DbTable_GradetamanhosHasLegendaMedidas();
                            $newData = array('GRA_ID'=>$id , 'LGM_ID'=>$lgm);
                            $obj->insert($newData);
                        }
                        
                        $fsc = new Sistema_Model_DbTable_GradetamanhosHasCat();
                        $fsc->delete('GRA_ID = '.$id);
                        foreach($formData['SEG_CAT'] as $key => $arr_seg){
                            foreach($arr_seg as $seg){
                                $data_arr = array(
                                    'GRA_ID' => $id,
                                    'CTS_ID' => $key,
                                    'CAT_ID' => $seg,
                                );
                                $fsc->insert($data_arr);
                            }
                        }
                        
                    }
                    
                    if(strlen($_FILES[$this->_file_col]['tmp_name']) > 1){
                        $img = glob($this->dir.$nome_img.'.*');
                        foreach($img as $filetemp) $filename = $filetemp;
                        imagem::reizeFull($filename,$filename, '200', '200');
                    }  
                    
                    $this->_helper->redirector('index');
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                Zend_Loader::loadClass('errordb','library');
                echo '<script>alert("'.Errordb::descricaoError($ex->getCode()).'");</script>';
                echo $ex->getMessage();
                $this->form->populate($formData);
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $data = $this->obj->fetchRow($this->_pk . ' = ' . $id)->toArray();
                $this->form->populate($data);
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {   
            $data = array($this->_sta_col => 0);
            $ok = (bool) $this->obj->update($data, $this->_pk . ' = ' . $id);
            
            Zend_Loader::loadClass('imagem','library');
            imagem::delete($id,$this->dir);
        }       
        echo json_encode(array('ok' => $ok));
    }
    
    // combo box
    public function combocatAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = TRUE;
        $html = '';
        $id = $this->_getParam('id', 0);
        $seg = $this->_getParam('seg', 0);
        $cat_id = 0;
        
        if($id > 0){
            $data = $this->obj->fetchRow($this->_pk . ' = ' . $id);
            $cat_id = $data['CAT_ID'];
        }

        $where = ' CTS_ID = '.$seg;
        //$obj = new Sistema_Model_DbTable_Categoria();
        //$result = $obj->fetchAll($obj->select()->where($where)->order('CAT_NOM ASC'));
        $query = 'SELECT SQL_CACHE CAT_ID,CAT_NOM FROM CATEGORIA WHERE '.$where.' ORDER BY CAT_NOM ASC';
        $result = $this->db->fetchAll($query);
        
        $html .= '<option value="0">Todos</option>';
        foreach($result as $res){
            $selected = ($cat_id == $res['CAT_ID']) ? 'selected=""':'';
            $html .= '<option value="'.$res['CAT_ID'].'" '.$selected.'>'.$res['CAT_NOM'].'</option>';
        }
        
        echo json_encode(array('ok' => $ok,'html'=>$html));
    }
    
    public function medidasAction() {
        
        $this->view->db = $this->db;
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_medidas.js?1='.rand(99,99999));
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js?1=2');
        
        if($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if(1) {
                    $id = (int) $formData[$this->_pk];
                    
                    $this->db->delete('GRADETAMANHOS_HAS_MEDIDAS',$this->_pk . ' = ' . $id);
                    foreach($formData['med'] as $tam => $legs){
                        foreach($legs as $leg => $val){
                            $data = array(
                                'GRA_ID'=>$id,
                                'TAM_ID'=>$tam,
                                'LGM_ID'=>$leg,
                                'GTM_VAL'=>$val
                            );
                            $this->db->insert('GRADETAMANHOS_HAS_MEDIDAS', $data);
                        }    
                    }
                    
                    $this->db->delete('GRADETAMANHOS_HAS_MEDINI', 'GRA_ID = '.$id);
                    foreach($formData['medini'] as $key => $medini) {
                        $data_arr = array(
                            'GRA_ID' => $id,
                            'LGM_ID' => $key,
                            'GMI_VAL' => $medini,
                        );
                        $this->db->insert('GRADETAMANHOS_HAS_MEDINI', $data_arr);
                    }
                    
                    $this->db->delete('GRADETAMANHOS_HAS_REDCOS', 'GRA_ID = '.$id);
                    foreach($formData['redcos'] as $key => $redcos) {
                        $data_arr = array(
                            'GRA_ID' => $id,
                            'LGM_ID' => $key,
                            'GRC_VAL' => $redcos,
                        );
                        $this->db->insert('GRADETAMANHOS_HAS_REDCOS', $data_arr);
                    }
                    
                    $this->db->delete('GRADETAMANHOS_HAS_AMPTAM', 'GRA_ID = '.$id);
                    foreach($formData['amptam'] as $key => $amptam) {
                        $data_arr = array(
                            'GRA_ID' => $id,
                            'LGM_ID' => $key,
                            'GAT_VAL' => $amptam,
                        );
                        $this->db->insert('GRADETAMANHOS_HAS_AMPTAM', $data_arr);
                    }
                    
                    $this->_helper->redirector('index');
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                Zend_Loader::loadClass('errordb','library');
                echo '<script>alert("'.Errordb::descricaoError($ex->getCode()).'");</script>';
                echo $ex->getMessage();
                $this->form->populate($formData);
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $query = 'SELECT SQL_CACHE * FROM GRADETAMANHOS WHERE '.$this->_pk . ' = ' . $id;
                $data = $this->db->fetchRow($query);
                $this->view->data = $data;
                
                $query = 'SELECT SQL_CACHE g.* FROM GRADETAMANHOS_HAS_TAMANHOS g, TAMANHOS t WHERE g.TAM_ID = t.TAM_ID AND t.TAM_STA = 1 AND g.'.$this->_pk . ' = ' . $id;
                $tam = $this->db->fetchAll($query);
                $this->view->tam = $tam;
                
                $query = 'SELECT SQL_CACHE g.* FROM GRADETAMANHOS_HAS_LEGMED g, LEGENDAMEDIDAS l WHERE g.LGM_ID = l.LGM_ID AND l.LGM_STA = 1 AND g.'.$this->_pk . ' = ' . $id;
                $leg = $this->db->fetchAll($query);
                $this->view->leg = $leg;
                
                $query = 'SELECT SQL_CACHE * FROM GRADETAMANHOS_HAS_MEDINI WHERE '.$this->_pk . ' = ' . $id;
                $row = $this->db->fetchAll($query);
                $medini = array();
                foreach($row as $r) $medini[$r['LGM_ID']] = $r['GMI_VAL'];
                $this->view->medini = $medini;
                
                $query = 'SELECT SQL_CACHE * FROM GRADETAMANHOS_HAS_REDCOS WHERE '.$this->_pk . ' = ' . $id;
                $row = $this->db->fetchAll($query);
                $redcos = array();
                foreach($row as $r) $redcos[$r['LGM_ID']] = $r['GRC_VAL'];
                $this->view->redcos = $redcos;
                
                $query = 'SELECT SQL_CACHE * FROM GRADETAMANHOS_HAS_AMPTAM WHERE '.$this->_pk . ' = ' . $id;
                $row = $this->db->fetchAll($query);
                $amptam = array();
                foreach($row as $r) $amptam[$r['LGM_ID']] = $r['GAT_VAL'];
                $this->view->amptam = $amptam;
                
            }
        }
    }
    
    public function filtrocombocatAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = TRUE;
        $html = '';
        $id = $this->_getParam('id', 0);

        $where = ' CTS_ID = '.$id;
        //$obj = new Sistema_Model_DbTable_Categoria();
        //$result = $obj->fetchAll($obj->select()->where($where)->order('CAT_NOM ASC'));
        $query = 'SELECT SQL_CACHE CAT_ID,CAT_NOM FROM CATEGORIA WHERE '.$where.' ORDER BY CAT_NOM ASC';
        $result = $this->db->fetchAll($query);
        
        $html .= '<option value="">Todas Categorias</option>';

        foreach($result as $res){
            $selected = ($cat_id == $res['CAT_ID']) ? 'selected=""':'';
            $html .= '<option value="'.$res['CAT_ID'].'" '.$selected.'>'.$res['CAT_NOM'].'</option>';
        }

        echo json_encode(array('ok' => $ok,'html'=>$html));
    }
}